<script setup lang="ts">
import dayjs from "dayjs";
import { message } from "@/utils/message";
import { customerLeaderData_performance_p } from "@/api/customer"
import { callOrder_listByStaff,performance,callorder } from "@/api/outbound"
import { ref, reactive, onMounted, h } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import type { PaginationProps } from "@pureadmin/table";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";

import Customer from "~icons/ri/customer-service-line";
import Refresh from "~icons/ep/refresh";

import Wavesurfer from "./wavesurfer/index.vue";

const props = defineProps({
  info: {
    type: Object,
    required: true
  },
})

const formRef = ref();
const statisticTabList = reactive([{
  name: '今日',
  created_at: ''
}, {
  name: '昨日',
  created_at: ''
}, {
  name: '本周',
  created_at: ''
}, {
  name: '上周',
  created_at: ''
}, {
  name: '本月',
  created_at: ''
}, {
  name: '上月',
  created_at: ''
}, {
  name: '总计',
  created_at: ''
}])
const statisticTab = ref(0)
const statisticLoading = ref(false)
const statisticInfo = ref({
  call_connect_num: 0,
  call_unknow_num: 0,
  call_refuse_num: 0,
  call_intend_num: 0,
  // 点呼统计
  callAll: 0, // 呼叫总数
  answer: 0, // 应答数
  intend: 0, // 意向数
  talkTimeSum:0 // 通话总时长
});
const statusList = ref([{
  value: "noconnect",
  label: "未接通未确定"
}, {
  value: "unkown",
  label: "接通未确定"
}, {
  value: "refuse",
  label: "无意向"
}, {
  value: "intend",
  label: "有意向"
}])
const form = reactive({
  status: "",
  target_staff_id: props.info.id,
  orderType:"outboundCall",
  project: "",
  sourceId: "",
  rangeTime: "",
  phone: "",
  duration: "",
  isGain: "" // 领取状态
});
const dataList = ref([]);
const loading = ref(true);
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true
});
const caseMap={
  "NORMAL_CLEARING":"正常挂断",
  "ORIGINATOR_CANCEL":"主叫挂机",
  "MEDIA_TIMEOUT":"呼叫超时",
  "USER_BUSY":"用户忙",
  "CALL_REJECTED":"拒绝呼叫",
  "NO_ANSWER":"无应答",
  "UNALLOCATED_NUMBER":"空号",
  "NO_USER_RESPONSE":"久叫不应",
  "USER_NOT_REGISTERED":"用户未注册",
  "NO_ROUTE_DESTINATION":"无法路由",
  "NETWORK_OUT_OF_ORDER":"网络异常",
  "NORMAL_UNSPECIFIED":"未定义",
  "RECOVERY_ON_TIMER_EXPIRE":"呼叫超时",
  "INCOMPATIBLE_DESTINATION":"目的地不兼容",
  "NORMAL_TEMPORARY_FAILURE":"临时故障",
  "DESTINATION_OUT_OF_ORDER":"目的地异常"
}
const answerFlagMap={
  0:'接通',
  1:'坐席未接用户未接',
  2:'坐席接通用户未接通',
  3:'用户接通坐席未接通'
}
const columns= reactive<TableColumnList>([
  {
    label: "主叫号码",
    prop: "caller",
    minWidth: 100
  },
  {
    label: "外显号码",
    prop: "callerDisplay",
    minWidth: 120
  },
  {
    label: "被叫号码",
    prop: "called",
    minWidth: 120
  },
  {
    label: "归属地",
    prop: "numberArea",
    minWidth: 150
  },
  {
    label: "坐席",
    prop: "agentName",
    minWidth: 150
  },
  {
    label: "拨打时间",
    prop: "callTime",
    minWidth: 200,
    formatter: ({ callTime }) => dayjs(callTime).format("YYYY-MM-DD HH:mm:ss")
  },
  {
    label: "应答时长（秒）",
    prop: "talkTime",
    minWidth: 120,
    formatter: ({ talkTime }) =>{
        if(talkTime==0){
          return 0;
        }else{
          return Math.floor(talkTime/1000);
        }
    }
  },
  {
    label: "呼叫结果",
    prop: "answerFlag",
    minWidth: 200,
    formatter: ({ answerFlag }) =>{
      return answerFlagMap[answerFlag];
    }
  },
  {
    label: "客户状态",
    prop: "intention",
    minWidth: 130,
    formatter: ({ intention }) =>{
      let map={
        'unkown':'接通未确定',
        'refuse':'无意向',
        'intend':'有意向',
        '':'未确定'
      };
      return map[intention];
    }
  },
  {
    label: "领取状态",
    prop: "ext1",
    minWidth: 150,
    formatter: ({ ext1 }) =>{
      let map={
        'gain':'已领取',
        '':'未领取'
      };
      return map[ext1];
    }
  },
  {
    label: "挂断原因",
    prop: "hangupCause",
    minWidth: 150,
    formatter: ({ hangupCause}) =>{
      return caseMap[hangupCause];
    }
  },
  {
    label: "挂断处理",
    prop: "hangupDir",
    minWidth: 150,
    formatter: ({ hangupDir }) =>{
      let map={
        1:'主叫挂机',
        2:'被叫挂机',
        3:'系统挂机',
      };
      return map[hangupDir];
    }
  },
  {
    width: 120,
    label: "操作",
    fixed: "right",
    slot: "operation"
  }
]);


// 听录音
function handleListen(row) {
  if (!row.record) return message(`此条数据无录音文件！`, { type: "error" });
   addDialog({
    title: "录音详情",
    props: {
      formInline: {
        row,
      }
    },
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h( Wavesurfer ),
    beforeSure: (done, { options }) => {
      done()
    }
  });
}

function handleSizeChange(val: number) {
  pagination.pageSize=val;
  onSearch();
}

function handleCurrentChange(val: number) {
  pagination.currentPage=val;
  onSearch();
}

async function onSearch() {
  loading.value = true;
  // const { data } = await getOnlineLogsList(toRaw(form));
  // dataList.value = data.list;
  // pagination.total = data.total;
  // pagination.pageSize = data.pageSize;
  // pagination.currentPage = data.currentPage;

  callOrder_listByStaff({
    staffId: form.target_staff_id,
    orderType:"autoOutboundCall",
    size:pagination.pageSize,
    page:pagination.currentPage,
    task_id:form.sourceId,
    rangeTime:form.rangeTime.toString() || "",
    phone:form.phone,
    status:form.status,
    isGain:form.isGain
  }).then(res=>{
    if(res.code == 1000){
      loading.value = false;
      pagination.total = res.data.total
      dataList.value = res.data.list
    }
  })

  // setTimeout(() => {
  //   loading.value = false;
  // }, 500);
}

const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  onSearch();
};

onMounted(() => {
  onSearch();

  getTimeRanges()
  getPerformance()
});


/**
 * 获取各种时间范围
 * @returns {Object} 包含各种时间范围的对象
 */
function getTimeRanges() {
  const now = new Date();

  // 格式化日期为 YYYY-MM-DD HH:mm:ss
  const formatDate = (date) => {
    const pad = (num) => num.toString().padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
           `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
  };

  // 设置时间为当天的开始(00:00:00)或结束(23:59:59)
  const setTime = (date, isStart) => {
    date.setHours(isStart ? 0 : 23);
    date.setMinutes(isStart ? 0 : 59);
    date.setSeconds(isStart ? 0 : 59);
    date.setMilliseconds(0);
    return date;
  };

  // 今日
  const todayStart = setTime(new Date(now), true);
  const todayEnd = setTime(new Date(now), false);

  // 昨日
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  const yesterdayStart = setTime(new Date(yesterday), true);
  const yesterdayEnd = setTime(new Date(yesterday), false);

  // 本周
  const weekStart = new Date(now);
  weekStart.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1));
  const weekEnd = new Date(weekStart);
  weekEnd.setDate(weekStart.getDate() + 6);
  const thisWeekStart = setTime(new Date(weekStart), true);
  const thisWeekEnd = setTime(new Date(weekEnd), false);

  // 上周
  const lastWeekStart = new Date(weekStart);
  lastWeekStart.setDate(weekStart.getDate() - 7);
  const lastWeekEnd = new Date(lastWeekStart);
  lastWeekEnd.setDate(lastWeekStart.getDate() + 6);
  const prevWeekStart = setTime(new Date(lastWeekStart), true);
  const prevWeekEnd = setTime(new Date(lastWeekEnd), false);

  // 本月
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
  const thisMonthStart = setTime(new Date(monthStart), true);
  const thisMonthEnd = setTime(new Date(monthEnd), false);

  // 上月
  const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  const lastMonthEnd = new Date(now.getFullYear(), now.getMonth(), 0);
  const prevMonthStart = setTime(new Date(lastMonthStart), true);
  const prevMonthEnd = setTime(new Date(lastMonthEnd), false);

  statisticTabList[0].created_at = `${formatDate(todayStart)},${formatDate(todayEnd)}`
  statisticTabList[1].created_at = `${formatDate(yesterdayStart)},${formatDate(yesterdayEnd)}`
  statisticTabList[2].created_at = `${formatDate(thisWeekStart)},${formatDate(thisWeekEnd)}`
  statisticTabList[3].created_at = `${formatDate(prevWeekStart)},${formatDate(prevWeekEnd)}`
  statisticTabList[4].created_at = `${formatDate(thisMonthStart)},${formatDate(thisMonthEnd)}`
  statisticTabList[5].created_at = `${formatDate(prevMonthStart)},${formatDate(prevMonthEnd)}`
  statisticTabList[6].created_at = ''
}

function getPerformance() {
  statisticLoading.value = true
  if(activeName.value == 0) { // 群呼
    customerLeaderData_performance_p({
    staff_id: props.info.id,
    created_at: statisticTabList[statisticTab.value].created_at
  }).then(res => {
    statisticInfo.value = res.data;

    statisticLoading.value = false
  });
  }else{
    performance({
    staff_id: props.info.id,
    created_at: statisticTabList[statisticTab.value].created_at
  }).then(res => {
    statisticInfo.value = res.data;

    statisticLoading.value = false
  });
  }
  
}
function getCallPerformance(){
  statisticLoading.value = true
  performance({
    staff_id: props.info.id,
    created_at: statisticTabList[statisticTab.value].created_at
  }).then(res=>{
    if(res.code == 1000){
      statisticInfo.value = res.data;
      statisticLoading.value = false
    }
  })
}
const columns2 = reactive<TableColumnList>([

  {
    label: "被叫号码",
    prop: "called",
    minWidth: 120
  },
  {
    label: "坐席",
    prop: "agentName",
    minWidth: 150
  },
  {
    label: "拨打时间",
    prop: "callTime",
    minWidth: 200,
    formatter: ({ callTime }) => dayjs(callTime).format("YYYY-MM-DD HH:mm:ss")
  },
  {
    label: "应答时长（秒）",
    prop: "talkTime",
    minWidth: 120,
    formatter: ({ talkTime }) =>{
        if(talkTime==0){
          return 0;
        }else{
          return Math.floor(talkTime/1000);
        }
    }
  },
  {
    label: "呼叫结果",
    prop: "answerFlag",
    minWidth: 200,
    formatter: ({ answerFlag }) =>{
      return answerFlagMap[answerFlag];
    }
  },
  {
    label: "客户状态",
    prop: "intention",
    minWidth: 130,
    formatter: ({ intention }) =>{
      let map={
        'unkown':'接通未确定',
        'refuse':'无意向',
        'intend':'有意向',
        '':'未确定'
      };
      return map[intention];
    }
  },
  {
    label: "领取状态",
    prop: "ext1",
    minWidth: 150,
    formatter: ({ ext1 }) =>{
      let map={
        'gain':'已领取',
        '':'未领取'
      };
      return map[ext1];
    }
  },
  {
    label: "挂断原因",
    prop: "hangupCause",
    minWidth: 150,
    formatter: ({ hangupCause}) =>{
      return caseMap[hangupCause];
    }
  },
  {
    label: "挂断处理",
    prop: "hangupDir",
    minWidth: 150,
    formatter: ({ hangupDir }) =>{
      let map={
        1:'主叫挂机',
        2:'被叫挂机',
        3:'系统挂机',
      };
      return map[hangupDir];
    }
  },
  {
    width: 120,
    label: "操作",
    fixed: "right",
    slot: "operation"
  }
]);
function getCallLogList(){
  loading.value = true;
  callorder({
    staff_id:form.target_staff_id,
    created_at:form.rangeTime.toString() || "",
    keyword:"",
    intension:form.status,
    page:pagination.currentPage,
    pagesize:pagination.pageSize
  }).then(res=>{
    if(res.code == 1000){
      loading.value = false;
      pagination.total = res.data.total
      dataList.value = res.data.list
    }
  })
}
const activeName = ref(0);
function handleClick(tab) {
  // console.log(tab.index);
  pagination.currentPage = 1
  dataList.value = []
  if( tab.index == 0) { // 群呼
    onSearch() 
    getPerformance()
  }else{ // 点呼
    getCallPerformance()
    getCallLogList()
  }
}
const formatTime = milliseconds => {
  const seconds = Math.floor((milliseconds / 1000) % 60);
  const minutes = Math.floor((milliseconds / (1000 * 60)) % 60);
  const hours = Math.floor((milliseconds / (1000 * 60 * 60)) % 24);
  return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
};

</script>

<template>
  <div class="main">
    <div>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="群呼话单" :name="0">
          <div class="cardTab">
      <el-radio-group
        v-model="statisticTab"
        size="large"
        @change="getPerformance"
      >
        <el-radio-button
          v-for="(item, index) in statisticTabList"
          :key="index"
          :label="item.name"
          :value="index"
        />
      </el-radio-group>
    </div>
    <!-- 数据统计 -->
    <div class="statistics" v-loading="statisticLoading">
      <div class="box">
        <p>拨通总数</p>
        <span>{{ statisticInfo.call_connect_num }}</span>
      </div>
      <div class="box">
        <p>未确定意向</p>
        <span>{{ statisticInfo.call_unknow_num }}</span>
      </div>
      <div class="box">
        <p>无意向</p>
        <span>{{ statisticInfo.call_refuse_num }}</span>
      </div>
      <div class="box">
        <p>有意向</p>
        <span>{{ statisticInfo.call_intend_num }}</span>
      </div>
      <div class="l_t"></div>
      <div class="l_l"></div>
      <div class="r_t"></div>
      <div class="r_l"></div>
    </div>
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item prop="status">
        <el-select
          v-model="form.status"
          placeholder="客户状态"
          clearable
          class="w-[120px]!"
        >
          <el-option
            v-for="(item, index) in statusList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item prop="orderType">
        <el-select
          v-model="form.orderType"
          placeholder="话单类型"
          clearable
          class="w-[120px]!"
        >
          <el-option label="点呼话单" value="outboundCall" />
          <el-option label="群呼话单" value="autoOutboundCall" />
        </el-select>
      </el-form-item> -->
      
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri/search-line')"
          :loading="loading"
          @click="onSearch"
        >
          查询
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar
      title=""
      :columns="columns"
      @refresh="onSearch"
    >
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :size="size"
          adaptive
          :adaptiveConfig="{ offsetBottom: 108 }"
          :data="dataList"
          :columns="dynamicColumns"
          :pagination="{ ...pagination, size }"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              type="primary"
              :size="size"
              :icon="useRenderIcon(Customer)"
              @click="handleListen(row)"
            >
              听录音
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
        </el-tab-pane>
        <el-tab-pane label="点呼话单" :name="1">
          <div class="cardTab">
      <el-radio-group
        v-model="statisticTab"
        size="large"
        @change="getPerformance"
      >
        <el-radio-button
          v-for="(item, index) in statisticTabList"
          :key="index"
          :label="item.name"
          :value="index"
        />
      </el-radio-group>
    </div>
    <!-- 数据统计 -->
    <div class="statistics" v-loading="statisticLoading">
      <div class="box">
        <p>呼叫总数</p>
        <span>{{ statisticInfo.callAll }}</span>
      </div>
      <div class="box">
        <p>应答数</p>
        <span>{{ statisticInfo.answer }}</span>
      </div>
      <div class="box">
        <p>意向数</p>
        <span>{{ statisticInfo.intend }}</span>
      </div>
      <div class="box">
        <p>通话总时长</p>
        <span>{{ formatTime(statisticInfo.talkTimeSum) }}</span>
      </div>
      <div class="l_t"></div>
      <div class="l_l"></div>
      <div class="r_t"></div>
      <div class="r_l"></div>
    </div>
      <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item prop="status">
        <el-select
          v-model="form.status"
          placeholder="客户状态"
          clearable
          class="w-[120px]!"
        >
          <el-option
            v-for="(item, index) in statusList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item prop="orderType">
        <el-select
          v-model="form.orderType"
          placeholder="话单类型"
          clearable
          class="w-[120px]!"
        >
          <el-option label="点呼话单" value="outboundCall" />
          <el-option label="群呼话单" value="autoOutboundCall" />
        </el-select>
      </el-form-item> -->
      
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri/search-line')"
          :loading="loading"
          @click="onSearch"
        >
          查询
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar
      title=""
      :columns="columns2"
      @refresh="onSearch"
    >
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :size="size"
          adaptive
          :adaptiveConfig="{ offsetBottom: 108 }"
          :data="dataList"
          :columns="dynamicColumns"
          :pagination="{ ...pagination, size }"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              type="primary"
              :size="size"
              :icon="useRenderIcon(Customer)"
              @click="handleListen(row)"
            >
              听录音
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    
  </div>
</template>

<style scoped lang="scss">
.main {
  height: 100%;
  padding-top: 20px;
}

.statistics {
  width: 100%;
  height: 40px;
  background-color: #f3f6f9;
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30px;
  position: relative;

  .box {
    display: flex;
    align-items: center;
    font-size: 14px;

    p {
      color: #000;
      margin-right: 7px;
    }

    span {
      color: var(--pure-theme-menu-active-before);
      font-weight: bold;
    }
  }

  .l_t {
    position: absolute;
    left: 0;
    top: 0;
    width: 12px;
    height: 12px;
    border-top: 2px solid var(--pure-theme-menu-active-before);
    border-left: 2px solid var(--pure-theme-menu-active-before);
  }

  .l_l {
    position: absolute;
    right: 0;
    top: 0;
    width: 12px;
    height: 12px;
    border-top: 2px solid var(--pure-theme-menu-active-before);
    border-right: 2px solid var(--pure-theme-menu-active-before);
  }

  .r_t {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 12px;
    height: 12px;
    border-bottom: 2px solid var(--pure-theme-menu-active-before);
    border-left: 2px solid var(--pure-theme-menu-active-before);
  }

  .r_l {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 12px;
    height: 12px;
    border-bottom: 2px solid var(--pure-theme-menu-active-before);
    border-right: 2px solid var(--pure-theme-menu-active-before);
  }
}

:deep(.el-form) {
  padding-top: 20px;
  padding-left: 0;
}

.multipleInner {
  background-color: var(--pure-theme-menu-active-before);
  height: 45px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  font-size: 14px;
  color: #ffffff;

  b, p {
    margin-left: 3px;
  }

  .multipHandle {
    padding: 5px 8px;
    margin-left: 30px;
    display: flex;
    align-items: center;
    cursor: pointer;
    border-radius: 5px;
    transition: all 0.1s;

    svg {
      color: #ffffff;
    }

    &:hover {
      background-color: #ffffff;
      color: #000000;

      :deep(svg) {
        color: #000000;
      }
    }
  }
}
</style>